package com.youdianstar.app.ui.help

import android.Manifest
import android.app.Dialog
import android.view.View
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.google.android.material.tabs.TabLayout
import com.safframework.eventbus.EventBus
import com.youdianstar.app.BR
import com.youdianstar.app.R
import com.youdianstar.app.databinding.ActivityFaqBinding
import com.youdianstar.app.entity.FaqListItem
import com.youdianstar.app.entity.FaqQuestionItem
import com.youdianstar.app.support.imp.IFaqListener
import com.youdianstar.app.util.AppDialogUtil
import com.youdianstar.app.common.ConfigKey
import com.youdianstar.app.common.Extra
import com.youdianstar.app.common.base.BaseActivity
import com.youdianstar.app.common.ex.setThrottleListener
import com.youdianstar.app.common.ex.toJson
import com.youdianstar.app.common.network.BaseApiStateObserver
import com.youdianstar.app.common.util.Tool

import com.youdianstar.app.common.util.dialog.DialogUtil
import com.youdianstar.app.adapter.FaqItemAdapter
import com.youdianstar.app.util.DataAppManager
import com.youdianstar.app.common.DataCode
import com.youdianstar.app.common.entity.BusEntity
import com.youdianstar.app.common.auko.startActivity
import org.koin.androidx.viewmodel.ext.android.viewModel


/**
 * File: FaqListActivity
 * Author: 82149 Create: 2021/11/9 11:08
 * Changes (from 2021/11/9)
 * --------------------------------------------------
 * description: Faq 列表数据
 * ---------------------------------------------------
 *
 */
class FaqListActivity :BaseActivity<ActivityFaqBinding,FaqViewModel>(){
    override fun layoutId(): Int = R.layout.activity_faq

    override fun initVariableId(): Int = BR.viewModel

    override fun initViewModel(): FaqViewModel {
        val model : FaqViewModel by viewModel()
        return model
    }


    private val mTabTitle : MutableList<String> = mutableListOf()
    /**
     * 分类: 租借、支付、设备、其他
     */
    private var typeIndex = 0
    private var isFirstLoad = false

    //数据 Faq list
    private val listData = mutableListOf<FaqListItem>()
    private val itemsList = mutableListOf<FaqQuestionItem>()
    private var mListAdapter : FaqItemAdapter?=null
    private var ctDialog : Dialog?=null
    private var whatsNum : String?=null
    private var phoneNum : String?=null
    private var emailStr : String?=null
    private var wechatLink : String?=null
    //var zaloLink : String?=null

    override fun initViewLayout() {
        super.initViewLayout()
        mBinding.headBar.initTitle(this,getString(R.string.menu_helpCentre))

        mBinding.rcyList.layoutManager = LinearLayoutManager(this)
        mListAdapter = FaqItemAdapter(this, itemsList, object :IFaqListener{
            override fun onQuestionClick(item: FaqQuestionItem) {
                startActivity<FaqDetailActivity>(Extra.IT_DATA to item.toJson())
            }
        })
        mBinding.rcyList.adapter = mListAdapter

        mBinding.swFaq.setOnChildScrollUpCallback(object : SwipeRefreshLayout.OnChildScrollUpCallback{
            override fun canChildScrollUp(parent: SwipeRefreshLayout, child: View?): Boolean {
                val linearLayoutManager = mBinding.rcyList.layoutManager as LinearLayoutManager
                return linearLayoutManager.findFirstCompletelyVisibleItemPosition() != 0;
            }
        })
        mBinding.swFaq.setOnRefreshListener { 
            // 刷新时重新加载硬编码数据
            val hardcodedData = getHardcodedFAQData()
            setFaqSortData(hardcodedData)
            mBinding.swFaq.isRefreshing = false
        }

        mBinding.faqTbType.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener{
            override fun onTabSelected(tab: TabLayout.Tab?) {
                val selectIndex = tab?.position ?:0
                typeIndex = selectIndex
                updateTabSelectView(selectIndex)
                if (!isFirstLoad)
                    getSortListData(selectIndex)
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {}

            override fun onTabReselected(tab: TabLayout.Tab?) {}
        })
    }

    override fun initData() {
        super.initData()
        // 只显示三个标签：订单问题、设备问题、其他（删除支付问题）
        mTabTitle.run {
            add(getString(R.string.help_rentalOrder))
            add(getString(R.string.help_device))
            add(getString(R.string.help_others))
        }
        // 使用硬编码的联系方式，参考 iOS 项目
        whatsNum = DataAppManager.instance.getConfig(ConfigKey.WhatsApp)
        phoneNum = getString(R.string.faq_other_contact_phone_content) // 硬编码: 0835001799
        emailStr = getString(R.string.faq_other_email_content) // 硬编码: youdianstar@gmail.com
        wechatLink = DataAppManager.instance.getConfig(ConfigKey.WechatQrLink)
        //zaloLink = DataAppManager.instance.getConfig(ConfigKey.ZaloQrLink)
        isFirstLoad = true
        initTabLayout(mTabTitle)
        
        // 使用硬编码数据，不再调用接口
        val hardcodedData = getHardcodedFAQData()
        setFaqSortData(hardcodedData)
        mBinding.swFaq.isRefreshing = false
        isFirstLoad = false

        EventBus.post(BusEntity(DataCode.CLOSE_DRAWER))//关闭侧边栏
    }
    
    override fun initLiveObserver() {
        super.initLiveObserver()
        // 已改为使用硬编码数据，不再需要监听接口
    }

    override fun initClickEvent() {
        // 意见反馈按钮已隐藏，无需处理点击事件
        // mBinding.tvFeedbackOp.setThrottleListener {
        //     startActivity<FeedbackActivity>()
        // }

        // 联系客服按钮 - 已取消隐藏
        mBinding.ivCus.setThrottleListener {
            showContactDialog()
        }
    }

    private fun initTabLayout(titles : MutableList<String>){
        mBinding.faqTbType.let { layout->
            layout.removeAllTabs()
            for ((index,title) in titles.withIndex()){
                val tabItem = layout.newTab()
                tabItem.setCustomView(R.layout.layout_tab_faq)
                tabItem.tag = title
                layout.addTab(tabItem, index==0)
                tabItem.customView?.let { tabView->
                    val tvTabTitle: TextView = tabView.findViewById(R.id.tabText)
                    val tvTabInner: TextView = tabView.findViewById(R.id.tabInner)
                    tvTabTitle.text = title
                    tvTabInner.text = title
                }
            }
            layout.tabMode = TabLayout.MODE_FIXED
            layout.setScrollPosition(0,0F, false)
            updateTabSelectView(0)
        }
    }

    private fun updateTabSelectView(position:Int){
        mBinding.faqTbType.let { layout->
            val tabCount = layout.tabCount
            for (index in 0 until tabCount){
                val tabItem = layout.getTabAt(index)
                tabItem?.customView?.let {tabView->
                    val tvTabTitle: TextView = tabView.findViewById(R.id.tabText)
                    val lgShadow: ConstraintLayout = tabView.findViewById(R.id.shadow_view)
                    tvTabTitle.visibility = if (index==position) View.INVISIBLE else View.VISIBLE
                    lgShadow.visibility = if (index==position) View.VISIBLE else View.INVISIBLE
                }
            }
        }
    }


    /**
     * 获取硬编码的FAQ数据
     * 参考 iOS 项目的实现
     */
    private fun getHardcodedFAQData(): List<FaqQuestionItem> {
        val faqList = mutableListOf<FaqQuestionItem>()
        
        // 订单问题 (type=3) - 对应第一个标签"订单问题"
        faqList.add(FaqQuestionItem(
            id = 3001,
            title = getString(R.string.faq_order_charging_rule_title),
            content = getString(R.string.faq_order_charging_rule),
            type = 3  // 订单问题
        ))
        
        faqList.add(FaqQuestionItem(
            id = 3002,
            title = getString(R.string.faq_order_still_charging_title),
            content = getString(R.string.faq_order_still_charging_content),
            type = 3  // 订单问题
        ))
        
        // 设备问题 (type=4) - 对应第二个标签"设备问题"
        faqList.add(FaqQuestionItem(
            id = 4001,
            title = getString(R.string.faq_device_not_ejected_title),
            content = getString(R.string.faq_device_not_ejected_content),
            type = 4  // 设备问题
        ))
        
        faqList.add(FaqQuestionItem(
            id = 4002,
            title = getString(R.string.faq_device_cannot_charge_title),
            content = getString(R.string.faq_device_cannot_charge_content),
            type = 4  // 设备问题
        ))
        
        faqList.add(FaqQuestionItem(
            id = 4003,
            title = getString(R.string.faq_device_how_to_return_title),
            content = getString(R.string.faq_device_how_to_return_content),
            type = 4  // 设备问题
        ))
        
        // 其他问题 (type=9) - 对应第三个标签"其他"
        faqList.add(FaqQuestionItem(
            id = 9001,
            title = getString(R.string.faq_other_contact_phone_title),
            content = getString(R.string.faq_other_contact_phone_content),
            type = 9  // 其他问题
        ))
        
        faqList.add(FaqQuestionItem(
            id = 9002,
            title = getString(R.string.faq_other_email_title),
            content = getString(R.string.faq_other_email_content),
            type = 9  // 其他问题
        ))
        
        faqList.add(FaqQuestionItem(
            id = 9003,
            title = getString(R.string.faq_other_address_title),
            content = getString(R.string.faq_other_address_content),
            type = 9  // 其他问题
        ))
        
        return faqList
    }

    /**设置数据*/
    private fun setFaqSortData(data: List<FaqQuestionItem>){
        listData.clear()
//        val sortList = mutableListOf<FaqListItem>()
        if (data.isNotEmpty()){
            data.groupBy { question->
                question.type
            }.entries.sortedBy{ item->
                item.key
            }.forEach{ qItem->
                listData.add(FaqListItem(qItem.key,qItem.value[0].title,qItem.value))
            }
        }
        getSortListData(typeIndex)
    }

    /**
     * 从分组好的列表中筛选数据
     * @param tabIndex 标签索引: 0-订单问题, 1-设备问题, 2-其他
     * 类型映射: type=3(订单问题), type=4(设备问题), type=9(其他问题)
     */
    private fun getSortListData(tabIndex: Int){
        itemsList.clear()
        // 标签顺序: [订单问题, 设备问题, 其他]
        // 对应的type: [3, 4, 9]
        val typeKeys = listOf(3, 4, 9)
        val targetType = if (tabIndex >= 0 && tabIndex < typeKeys.size) {
            typeKeys[tabIndex]
        } else {
            3  // 默认返回订单问题
        }
        
        listData.forEach { item ->
            if (item.type == targetType) {
                itemsList.addAll(item.faqList)
            }
        }
        mListAdapter?.notifyDataSetChanged()
    }

    //----------------------------------------------------------------

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
        super.onPermissionsGranted(requestCode, perms)
        if (requestCode == REQUEST_PERMISSION_CODE)
            callPhone()
    }

    private fun requestCallPermission() {
        phoneNum.let { phone ->
            val phoneCall = String.format(getString(R.string.Dialog_SelectCall_Message),phone)
            showActionDialog(phoneCall) {
                requestPermission(
                    getString(R.string.Call_Permission_Tip),
                    Manifest.permission.CALL_PHONE,
                    granted = {
                        callPhone()
                    })
            }
        }
    }

    private fun showContactDialog(){
        ctDialog = AppDialogUtil.instance.showContactDialog(this,
            phoneStr = phoneNum, emailStr = emailStr, wechatLink = wechatLink,
            callAction = {
            callPhone()
        },emailAction = {
            callEmail()
        })
    }

    private fun showActionDialog(msg :String, confirmAction: (() -> Unit) = { }){
        DialogUtil.instance.showNotifyDialog(this,
            title = getString(R.string.public_notice),
            msg = msg,leftAction = {

            },left = getString(R.string.public_cancel),
            rightAction = confirmAction,
            right = getString(R.string.profile_confirm),
            isShowLeft = true,isShowRight = true)
    }

    private fun callPhone(){
        phoneNum?.let { phone ->
            Tool.callPhone(this,phone)
        }
    }

    private fun callEmail(){
        emailStr?.let { email ->
            val emailCall = String.format(getString(R.string.Dialog_SelectEmail_Message),email)
            showActionDialog(emailCall) {
                Tool.callEmail(this,email)
            }
        }
    }

    private fun callWhatsapp(){
        whatsNum?.let { num ->
            val appCall = getString(R.string.Dialog_SelectWhatsapp_Message)
            showActionDialog(appCall) {
                Tool.callWhatsApp(this,num)
            }
        }
    }

    override fun onDestroy() {
        ctDialog?.let {
            if (it.isShowing)
                it.dismiss()
        }
        super.onDestroy()
    }
}